package net.simo.servicebook.controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;

import net.simo.servicebook.model.Person;
import net.simo.servicebook.model.security.User;

@Named
@ConversationScoped
public class PersonSearch implements Serializable {
	private static final long serialVersionUID = 250148018711530022L;

	@Inject
	private EntityManager em;

	@Inject
	private Conversation conversation;

	private String personName;
	private List<Person> searchResults;
	private List<Person> searchResultUsers;

	public void findPerson() {
		if (conversation.isTransient()) {
			conversation.begin();
		}
		this.searchResults = em.createQuery("from Person p where p.personName like :name", Person.class).setParameter("name", "%" + personName + "%").getResultList();
		List<User> users = em.createQuery("FROM User u where u.person.personName LIKE :name", User.class).setParameter("name", "%" + personName + "%").getResultList();
		this.searchResultUsers = new ArrayList<Person>();
		
		for (User user : users) {
			this.searchResultUsers.add(user.getPerson());
		}
		this.searchResults.removeAll(searchResultUsers);
	}

	public String getPersonName() {
		return personName;
	}

	public void setPersonName(String personName) {
		this.personName = personName;
	}

	@Produces
	@Named
	public List<Person> getSearchResults() {
		return searchResults;
	}
	
	@Produces
	@Named
	public List<Person> getSearchResultUsers() {
		return searchResultUsers;
	}
}
